#include "CNet.h"

IConnect* NewConnection(int* pTCPConnect_fd,int connectId,IRouter* router){
    Connection* connection=(Connection*)malloc(sizeof(Connection));
    printf("最开始创建连接时的地址 %p\n",connection);

    connection->TCPConnect_fd=*pTCPConnect_fd;
    connection->connectId=connectId;
    connection->router=router;
    connection->isClosed=0;// 初始为没有关闭

    connection->vtable.Start=Connection_Start;
    connection->vtable.Stop=Connection_Stop;
    connection->vtable.GetConnectID=Connection_GetConnectID;
    return (IConnect*)connection;
}

// 在一个独立的线程中，处理数据
void StartReader(void* self){
    Connection* connection=(Connection*)self;
    char buffer[512];
    int bytes_read;

    while(1){
        // 读取数据
        bytes_read = read(connection->TCPConnect_fd, buffer, sizeof(buffer));
        if (bytes_read <= 0) {
            if (bytes_read == 0) {
                printf("Client disconnected\n");
            } else {
                perror("read error");
            }
            break;
        }

        // 对读取的数据进行处理
        Request* request=NewRequest(connection,NewData(buffer,bytes_read));
        pthread_t request_thread;
        if (pthread_create(&request_thread, NULL, RequestHandle, (IRequest*)request) < 0) {
            perror("could not create thread");
            exit(EXIT_FAILURE);
        }
            
    }


}
void Connection_Start(void* self){
    printf("Connection_Start时self的地址 %p\n",self);
    Connection* connection=(Connection*)self;
    printf("Connection_Start时的地址 %p\n",connection);
    printf("连接开始 \n");              
    pthread_t reader_thread;
    // 开启一个线程，进行处理操作
    if (pthread_create(&reader_thread, NULL, StartReader, connection) < 0) {
        perror("could not create thread");
        exit(EXIT_FAILURE);
    }
    pthread_detach(reader_thread);

}
void Connection_Stop(void* self){
    Connection* connection=(Connection*)self;
    WaitConnectClose(self);
    FreeConnection(connection);
    printf("连接退出并清除fd \n");
}

void FreeConnection(Connection *connection){
    close(connection->TCPConnect_fd);
    free(connection);
}

int Connection_GetConnectID(void* self){
    Connection* connection=(Connection*)self;
    return connection->connectId;
}

void WaitConnectClose(void *self){
    Connection* connection=(Connection*)self;
    while(1){
        if(connection->isClosed==1){
            return;
        }else{
            continue;
        }
    }
}
